<template>
  <div class="add-exhibition-container">
    <div class="header">
      <h2>添加展览</h2>
      <el-button @click="goBack">返回</el-button>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="exhibition-form"
    >
      <el-form-item label="展览标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入展览标题" />
      </el-form-item>

      <el-form-item label="展览封面" prop="cover">
        <el-upload
          class="cover-uploader"
          action="/api/api/file/upload"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :headers="uploadHeaders"
          :http-request="customUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="cover-image" />
          <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="cover-tip">建议上传16:9比例的图片</div>
      </el-form-item>

      <el-form-item label="展览描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          rows="6"
          placeholder="请输入展览描述"
        />
      </el-form-item>

      <el-form-item label="展览时间" required>
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2" class="text-center">
          <span>至</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="上架"
          inactive-text="下架"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createExhibition } from '@/api/exhibition'
import { uploadFileWithPreview, getImageUrl } from '@/api/file'
import Cookies from 'js-cookie'

const router = useRouter()
const formRef = ref(null)
const imageUrl = ref('') // 用于本地预览的URL

// 表单数据
const form = reactive({
  title: '',
  cover: '',
  description: '',
  startTime: '',
  endTime: '',
  status: 0
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入展览标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传展览封面', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入展览描述', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
})

// 上传请求头
const uploadHeaders = computed(() => {
  return {
    'Authorization': 'Bearer ' + Cookies.get('Admin-Token')
  }
})

// 返回列表页
const goBack = () => {
  router.push('/exhibition')
}

// 自定义上传方法，支持本地预览
const customUpload = (options) => {
  const { file, onSuccess, onError } = options
  
  // 使用集中的文件服务进行上传
  uploadFileWithPreview(file, (previewUrl) => {
    imageUrl.value = previewUrl;
  })
    .then(response => {
      if (response.code === 200) {
        form.cover = response.data.url;
        onSuccess(response);
      } else {
        onError(new Error(response.message || '上传失败'));
        ElMessage.error('上传失败: ' + (response.message || '未知错误'));
      }
    })
    .catch(error => {
      onError(error);
      ElMessage.error('上传失败: ' + (error.message || '未知错误'));
    });
}

// 图片上传成功回调
const handleCoverSuccess = (res, file) => {
  if (res.code === 200) {
    form.cover = res.data.url
  } else {
    imageUrl.value = '' // 清除预览
    ElMessage.error('上传失败: ' + res.message)
  }
}

// 图片上传前的验证
const beforeCoverUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return (isJPG || isPNG) && isLt2M
}

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 创建提交数据的副本，以便格式化日期
        const submitData = { ...form }
        
        // 确保日期字段存在且格式正确 (ISO格式，保留T分隔符)
        if (submitData.startTime) {
          const startDate = new Date(submitData.startTime)
          submitData.startTime = startDate.toISOString().slice(0, 19)
        } else {
          ElMessage.error('请选择开始时间')
          return
        }
        
        if (submitData.endTime) {
          const endDate = new Date(submitData.endTime)
          submitData.endTime = endDate.toISOString().slice(0, 19)
        } else {
          ElMessage.error('请选择结束时间')
          return
        }
        
        console.log('提交数据:', submitData) // 调试用
        await createExhibition(submitData)
        ElMessage.success('添加成功')
        router.push('/exhibition')
      } catch (error) {
        console.error('添加展览失败', error)
        ElMessage.error('添加展览失败: ' + (error.message || '未知错误'))
      }
    } else {
      return false
    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.add-exhibition-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.exhibition-form {
  max-width: 800px;
}

.cover-uploader {
  width: 300px;
  height: 169px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 30px;
  height: 30px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}
</style> 